import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageDraw, ImageTk
import os

class BorderGenerator:
    def __init__(self, root):
        self.root = root
        self.root.title("牌匾边框生成器")
        self.root.geometry("800x600")
        
        # 初始化变量
        self.original_image = None
        self.display_image = None
        self.image_path = None
        self.bg_image = None  # 背景图片
        
        # 合规图片尺寸
        self.compliant_width = 2500
        self.compliant_height = 676
        
        # 居中显示窗口
        self.center_window()
        
        # 加载背景图片
        self.load_bg_image()
        
        self.setup_ui()
    
    def center_window(self):
        """将窗口居中显示"""
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f'{width}x{height}+{x}+{y}')
    
    def load_bg_image(self):
        """加载背景图片"""
        bg_path = os.path.join(os.path.dirname(__file__), "bg.png")
        if os.path.exists(bg_path):
            try:
                self.bg_image = Image.open(bg_path)
                # 转换为RGBA模式以支持透明度
                if self.bg_image.mode != "RGBA":
                    self.bg_image = self.bg_image.convert("RGBA")
            except Exception as e:
                print(f"无法加载背景图片: {e}")
                self.bg_image = None
        else:
            print("未找到背景图片 bg.png")
            self.bg_image = None
    
    def setup_ui(self):

        # 说明
        desc = tk.Label(self.root, text="上传图片前，请调整为合规尺寸", font=("Arial", 10))
        desc.pack(pady=5)
        
        # 主框架
        main_frame = tk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 左侧控制面板
        control_frame = tk.LabelFrame(main_frame, text="图片设置", padx=15, pady=15, font=("Arial", 10, "bold"))
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 15))
        
        # 按钮区域
        button_frame = tk.Frame(control_frame)
        button_frame.pack(fill=tk.X, pady=(20, 0))
        
        # 调整图片尺寸按钮
        resize_btn = tk.Button(
            button_frame, text="调整图片尺寸", command=self.resize_image,
            bg="#9C27B0", fg="white", font=("Arial", 10), width=15
        )
        resize_btn.pack(pady=5)
        
        # 上传图片按钮
        upload_btn = tk.Button(
            button_frame, text="上传图片", command=self.upload_image,
            bg="#4CAF50", fg="white", font=("Arial", 10), width=15
        )
        upload_btn.pack(pady=5)
        
        # 生成边框图片按钮
        generate_btn = tk.Button(
            button_frame, text="生成边框图片", command=self.generate_compliant_image,
            bg="#2196F3", fg="white", font=("Arial", 10), width=15
        )
        generate_btn.pack(pady=5)
        
        # 保存图片按钮
        save_btn = tk.Button(
            button_frame, text="保存图片", command=self.save_image,
            bg="#FF9800", fg="white", font=("Arial", 10), width=15
        )
        save_btn.pack(pady=5)
        
        # 右侧预览区域
        preview_frame = tk.LabelFrame(main_frame, text="预览", padx=10, pady=10, font=("Arial", 10, "bold"))
        preview_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        self.preview_label = tk.Label(preview_frame, text="请上传一张图片", font=("Arial", 10))
        self.preview_label.pack(expand=True)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪 - 请上传图片")
        status_bar = tk.Label(self.root, textvariable=self.status_var, bd=1, 
                             relief=tk.SUNKEN, anchor=tk.W, bg="#f0f0f0")
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    def upload_image(self):
        """上传图片"""
        file_path = filedialog.askopenfilename(
            title="选择图片文件",
            filetypes=[
                ("所有图片", "*.png *.jpg *.jpeg *.bmp *.gif *.tiff"),
                ("PNG", "*.png"),
                ("JPEG", "*.jpg *.jpeg"),
                ("BMP", "*.bmp"),
                ("GIF", "*.gif"),
                ("TIFF", "*.tiff")
            ]
        )
        
        if file_path and os.path.exists(file_path):
            try:
                self.image_path = file_path
                self.original_image = Image.open(file_path)
                # 转换为RGBA模式以支持透明度
                if self.original_image.mode != "RGBA":
                    self.original_image = self.original_image.convert("RGBA")
                
                self.display_image = self.original_image.copy()
                self.show_preview()
                self.status_var.set(f"已加载图片: {os.path.basename(file_path)}")
            except Exception as e:
                messagebox.showerror("错误", f"无法加载图片: {str(e)}")
    
    def resize_image(self):
        """调整图片尺寸到合规尺寸"""
        if self.original_image is None:
            messagebox.showwarning("警告", "请先上传一张图片")
            return
        
        try:
            self.status_var.set("正在调整图片尺寸...")
            self.root.update()
            
            # 调整原始图片到合规尺寸 (2500x676)
            self.display_image = self.original_image.resize((self.compliant_width, self.compliant_height), Image.Resampling.LANCZOS)
            self.show_preview()
            
            self.status_var.set("图片尺寸调整完成")
        except Exception as e:
            messagebox.showerror("错误", f"调整图片尺寸时出错: {str(e)}")
            self.status_var.set("调整失败")
    
    def show_preview(self):
        """显示预览图片"""
        if self.display_image:
            # 调整图片大小以适应预览区域
            img_width, img_height = self.display_image.size
            max_width, max_height = 500, 400
            
            scale = min(max_width/img_width, max_height/img_height)
            new_width = int(img_width * scale)
            new_height = int(img_height * scale)
            
            resized_img = self.display_image.resize((new_width, new_height), Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            
            self.preview_label.configure(image=photo, text="")
            self.preview_label.image = photo  # 保持引用
    
    def generate_compliant_image(self):
        """生成边框图片"""
        if self.original_image is None:
            messagebox.showwarning("警告", "请先上传一张图片")
            return
        
        try:
            self.status_var.set("正在生成边框图片...")
            self.root.update()
            
            # 生成合规尺寸的图片
            self.display_image = self.create_compliant_image()
            self.show_preview()
            
            self.status_var.set("边框图片生成完成")
        except Exception as e:
            messagebox.showerror("错误", f"生成边框图片时出错: {str(e)}")
            self.status_var.set("生成失败")
    
    def create_compliant_image(self):
        """创建合规尺寸的图片"""
        if self.original_image is None:
            return None
        
        # 调整原始图片到合规尺寸 (2500x676)
        compliant_image = self.original_image.resize((self.compliant_width, self.compliant_height), Image.Resampling.LANCZOS)
        
        # 如果有背景图片，则将合规图片居中放在背景图片上
        if self.bg_image:
            # 获取背景图片尺寸
            bg_width, bg_height = self.bg_image.size
            
            # 创建结果图像，基于背景图片
            result_image = self.bg_image.copy()
            
            # 计算合规图片在背景图片上的居中位置
            x = (bg_width - self.compliant_width) // 2
            y = (bg_height - self.compliant_height) // 2
            
            # 将合规图片粘贴到背景图片的中央
            result_image.paste(compliant_image, (x, y), compliant_image)
            
            return result_image
        else:
            # 如果没有背景图片，直接返回合规尺寸的图片
            return compliant_image
    
    def save_image(self):
        """保存图片"""
        if self.display_image is None:
            messagebox.showwarning("警告", "没有可保存的图片")
            return
        
        file_path = filedialog.asksaveasfilename(
            title="保存图片",
            defaultextension=".png",
            filetypes=[("PNG files", "*.png"), ("All files", "*.*")],
            initialfile="边框图片.png"
        )
        
        if file_path:
            try:
                self.display_image.save(file_path, "PNG")
                messagebox.showinfo("成功", f"图片已保存到: {file_path}")
                self.status_var.set("图片保存成功")
            except Exception as e:
                messagebox.showerror("错误", f"保存图片时出错: {str(e)}")
                self.status_var.set("保存失败")

def main():
    root = tk.Tk()
    app = BorderGenerator(root)
    root.mainloop()

if __name__ == "__main__":
    main()